#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import ${package}.core.utils.JacksonUtil;
import feign.FeignException;
import feign.Logger;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @Author: shenyang
 * @CreateTime: 2023-09-25  16:33
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
public class FeignResultDecoder implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        if (response.body() == null) {
            throw new DecodeException(response.status(), "没有返回有效的数据", response.request());
        }
        String bodyStr = Util.toString(response.body().asReader(Util.UTF_8));
        if (StringUtils.isNotEmpty(bodyStr)) {
//            Result result = FeignResultDecoder.json2obj(bodyStr, type);
            JavaType javaType = TypeFactory.defaultInstance().constructType(type);
            return JacksonUtil.json2Bean(bodyStr, javaType);
            //对结果进行转换
//            Result result = FeignResultDecoder.json2obj(bodyStr, type);
//            可以处理成自己需要返回的类
//            return result;
        }
        return null;
    }

    /**
     * feignClient配置日志级别 * * @return
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 请求和响应的头信息,请求和响应的正文及元数据
        return Logger.Level.FULL;
    }

    public static <T> T json2obj(String jsonStr, Type targetType) {
        try {
            JavaType javaType = TypeFactory.defaultInstance().constructType(targetType);
            return new ObjectMapper().readValue(jsonStr, javaType);
        } catch (IOException e) {
            throw new IllegalArgumentException("将JSON转换为对象时发生错误:" + jsonStr, e);
        }
    }

}
